import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
import '../utils/baseUrl.dart';
import '../components/toast.dart';
import '../components/loading.dart';

class HttpClient {
  static const String baseUrl = BaseUrl.baseUrl;  // 替换为你的API域名
  static String? _token;  // 存储token

  // 设置token
  static void setToken(String token) {
    _token = token;
  }

  // 获取token
  static String? getToken() {
    return _token;
  }

  // 清除token
  static void clearToken() {
    _token = null;
  }

  // 处理响应
  static dynamic _handleResponse(http.Response response) {
 
    switch (response.statusCode) {
      case 200:
        try {
          var responseJson = json.decode(response.body);
          if (responseJson['code'] == 200) {
            return responseJson['data'];
          } else if (responseJson['code'] == 401) {
            // throw FetchDataException('Error during GET request: ${responseJson['message']}');
          } else {
            return responseJson;
          }
          // print('解析后的数据类型: ${responseJson.runtimeType}');
          // print('解析后的数据: $responseJson');
          // return responseJson;
        } catch (e) {
          print('JSON解析错误: $e');
          return response.body;
        }
      case 401: // 未授权
        clearToken();
        throw UnauthorizedException('Unauthorized');
      case 403: // 禁止访问
        throw ForbiddenException('Forbidden');
      case 404: // 未找到
        throw NotFoundException('Not found');
      case 500: // 服务器错误
        throw ServerException('Server error');
      default:
        throw FetchDataException(
            'Error occurred while communicating with Server with StatusCode : ${response.statusCode}');
    }
  }

  // 获取headers
  static Map<String, String> _getHeaders() {
    Map<String, String> headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };
    
    if (_token != null) {
      headers['Authorization'] = 'Bearer $_token';
    }
    
    return headers;
  }

  // GET 请求
  static Future<dynamic> get(String endpoint, {Map<String, dynamic>? queryParams}) async {
    try {
      Loading.showLoading(message: '加载中...');
      var uri = Uri.parse('$baseUrl$endpoint');
      if (queryParams != null) {
        uri = uri.replace(queryParameters: queryParams);
      }

      final response = await http.get(
        uri,
        headers: _getHeaders(),
      );

      return _handleResponse(response);
    } catch (e) {
      throw FetchDataException('Error during GET request: $e');
    } finally {
      Loading.dismissLoading();
    }
  }

  // POST 请求
  static Future<dynamic> post(String endpoint, {dynamic body}) async {
    try {
      final response = await http.post(
        Uri.parse('$baseUrl$endpoint'),
        headers: _getHeaders(),
        body: json.encode(body),
      );

      return _handleResponse(response);
    } catch (e) {
      throw FetchDataException('Error during POST request: $e');
    }
  }

  // PUT 请求
  static Future<dynamic> put(String endpoint, {dynamic body}) async {
    try {
      final response = await http.put(
        Uri.parse('$baseUrl$endpoint'),
        headers: _getHeaders(),
        body: json.encode(body),
      );

      return _handleResponse(response);
    } catch (e) {
      throw FetchDataException('Error during PUT request: $e');
    }
  }

  // DELETE 请求
  static Future<dynamic> delete(String endpoint) async {
    try {
      final response = await http.delete(
        Uri.parse('$baseUrl$endpoint'),
        headers: _getHeaders(),
      );

      return _handleResponse(response);
    } catch (e) {
      throw FetchDataException('Error during DELETE request: $e');
    }
  }
}

// 自定义异常类
class AppException implements Exception {
  final String message;
  final String? prefix;

  AppException([this.message = '', this.prefix]);

  @override
  String toString() {
    return "$prefix$message";
  }
}

class FetchDataException extends AppException {
  FetchDataException([String? message])
      : super(message!, "Error During Communication: ");
}

class UnauthorizedException extends AppException {
  UnauthorizedException([String? message]) : super(message!, "Unauthorized: ");
}

class ForbiddenException extends AppException {
  ForbiddenException([String? message]) : super(message!, "Forbidden: ");
}

class NotFoundException extends AppException {
  NotFoundException([String? message]) : super(message!, "Not Found: ");
}

class ServerException extends AppException {
  ServerException([String? message]) : super(message!, "Server Error: ");
}
